import os
from ipfilterbase import IPFilter

class FilterManager:
    def __init__(self):
        self.filter = IPFilter()
        
        self.filterdir = os.path.join(utility.getConfigPath(), "ipfilter")
        self.userfile = os.path.join(self.filterdir, "ipfilter.txt")        
    
        self.enabled = utility.config.Read('ipfilter', "boolean")
        if self.enabled:
            self.loadFiles()
            
    def __nonzero__(self):
        return bool(self.filter and self.enabled)
    
    def __len__(self):
        return len(self.filter)
    
    def isEnabled(self):
        return self.enabled
    
    def enable(self, flag = True):
        if self.enabled == flag:
            return False
        
        self.enabled = flag
        utility.config.Write('ipfilter', flag, "boolean")
        
        if flag:
            self.loadFiles()
        else:
            self.clear()

    def loadFiles(self):
        files = os.listdir(self.filterdir)
        for filename in files:
            self.addFile(filename)
        
    def addFile(self, filename):
        return self.filter.readfile(os.path.join(self.filterdir, filename))
                    
    def includes(self, ip):
        return ip in self.filter

    def clear(self):
        self.filter.clear()
            
    def reloadFilter(self):
        self.clear()
        self.loadFiles()

    def removeRange(self, start, end):
        self.filter.remove(start, end)
        # TODO: Save in a the conf file
        
    def addRange(self, start, end = None, name = "Unknown"):
        self.filter.add(start, end)
    
        # Save them in a new file
        f = open(self.userfile, "a+")
        try:
            f.writelines(name + ":" + start + "-" + end)
        finally:
            f.close()
